#include "key.h"
#include "led.h"
#include "beep.h"

extern int ledHall;
extern int ledRoom;
extern int ledKitc;
extern int ledLave;

void key_init(void)
{
    pinMode(KEY1, INPUT);
    pinMode(KEY2, INPUT);
    pinMode(KEY3, INPUT);
    pinMode(KEY4, INPUT);
}

void KEY1_Interrupt(void)
{
    ledHall = !ledHall;
    led_hall(ledHall);
    beep_tips();
}

void KEY2_Interrupt(void)
{
    ledRoom = !ledRoom;
    led_room(ledRoom);
    beep_tips();
}

void KEY3_Interrupt(void)
{
    ledKitc = !ledKitc;
    led_kitc(ledKitc);
    beep_tips();
}

void KEY4_Interrupt(void)
{
    ledLave = !ledLave;
    led_lave(ledLave);
    beep_tips();
}

void keyExit_init(void)
{
    if(wiringPiISR(KEY1, INT_EDGE_FALLING, &KEY1_Interrupt) < 0)
    {
        printf("Unable to setup ISR\n");
    }

    if(wiringPiISR(KEY2, INT_EDGE_FALLING, &KEY2_Interrupt) < 0)
    {
        printf("Unable to setup ISR\n");
    }

    if(wiringPiISR(KEY3, INT_EDGE_FALLING, &KEY3_Interrupt) < 0)
    {
        printf("Unable to setup ISR\n");
    }

    if(wiringPiISR(KEY4, INT_EDGE_FALLING, &KEY4_Interrupt) < 0)
    {
        printf("Unable to setup ISR\n");
    }
}

int key_scan(int mode)
{
    static int key_up = 1;	//按键按松开标志

    if(mode)
    {
            key_up = 1;  	//支持连按
    }

    if(key_up && (digitalRead(KEY1) == 0)||(digitalRead(KEY2) == 0)
                      ||(digitalRead(KEY3) == 0)||(digitalRead(KEY4) == 0))
    {
            delay(50);	 //去抖动
            key_up = 0;

            if(digitalRead(KEY1) == 0)   	 return KV_MOD;
            else if(digitalRead(KEY2) == 0)   return KV_ERA;
            else if(digitalRead(KEY3) == 0)   return KV_ADD;
            else if(digitalRead(KEY4) == 0)   return KV_SUB;

    }else if((digitalRead(KEY1) == 1) && (digitalRead(KEY2) == 1)
                   && (digitalRead(KEY3) == 1) && (digitalRead(KEY4) == 1))
    {
            key_up = 1;
    }

    return 0;
}
